from bs4 import BeautifulSoup

from pyppeteer_util.base_pyppeteer import BasePyppeteer


class VideoFileScraper(BasePyppeteer):
    async def fetch_videos(self, selector):
        page = await self.setup_page()
        await page.goto(self.url)

        # 等待selector插件加载完毕 (偶尔会出现内容加载不出来的情况)
        await page.waitForSelector(selector, {'timeout': 30000})

        # 获取该元素的文本内容
        # element_text = await page.querySelectorEval(
        #     'video-js',
        #     '(element) => element.textContent'
        # )

        await page.waitForFunction(
            '''
            () => {
                try{
                    const element = document.querySelector("video.vjs-tech");
                    console.log(element)
                    const href = element ? element.getAttribute('src').trim() : "";
                    return element.getAttribute('src') !== '';
                }catch(error){
                    console.log(error);
                    return false;
                }
            }
            ''',
            {'timeout': 30000}  # 超时时间 30 秒
        )
        # 获取该元素的文本内容
        element_text = await page.querySelectorEval(
            'video-js#player1',
            '(element) => element.outerHTML'
        )

        await page.close()
        return element_text

    async def start(self):
        try:
            path = self.get_chrome_path()
            await self.create_browser(path)
            html_content = await self.fetch_videos('video-js')
            if not html_content:
                return []
            # 解析 HTML
            soup = BeautifulSoup(html_content, 'html.parser')
            video = soup.find('video', class_='vjs-tech')
            src = video.attrs['src']

            return src
        except Exception as e:
            print(f'Error: {e}')
        finally:
            await self.close_browser()